package nginx

import (
	appv1 "gitee.com/lxl18742045376/nginx-operator/api/v1"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

func NewDeploy(nginx *appv1.Nginx) *appsv1.Deployment {
	labels := map[string]string{"app.viper.run/v1": nginx.Name}
	selector := &metav1.LabelSelector{MatchLabels: labels}
	return &appsv1.Deployment{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "apps/v1",
			Kind:       "Deployment",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      nginx.Name,
			Namespace: nginx.Namespace,
			OwnerReferences: []metav1.OwnerReference{
				*metav1.NewControllerRef(nginx, schema.GroupVersionKind{
					Group:   appv1.GroupVersion.Group,
					Version: appv1.GroupVersion.Version,
					Kind:    "Nginx",
				}),
			},
		},
		Spec: appsv1.DeploymentSpec{
			Replicas: nginx.Spec.Size,
			Selector: selector,
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: labels,
				},
				Spec: corev1.PodSpec{
					Containers: newContainers(nginx),
				},
			},
		},
	}
}

func newContainers(nginx *appv1.Nginx) []corev1.Container {
	var containerPorts []corev1.ContainerPort
	for _, servicePort := range nginx.Spec.Ports {
		var cport corev1.ContainerPort
		cport.ContainerPort = servicePort.TargetPort.IntVal
		containerPorts = append(containerPorts, cport)
	}
	return []corev1.Container{
		{
			Name:            nginx.Name,
			Image:           nginx.Spec.Image,
			Ports:           containerPorts,
			Env:             nginx.Spec.Envs,
			Resources:       nginx.Spec.Resources,
			ImagePullPolicy: corev1.PullIfNotPresent,
		},
	}
}
